package com.leo.javase.jdbc.db;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

public class DBCPUtils {
	//数据源
	private static DataSource dataSource;
	//加载配配置文件
	private static final String CONFIG = "/dbcp.properties";
	/**
	 * 默认的构造函数
	 */
	private DBCPUtils(){
		initDbcp();
	}
	/**
	 * 初始化方法
	 */
	private static void initDbcp() {
		Properties prop = new Properties();
		try {
			prop.load(DBCPUtils.class.getResourceAsStream(CONFIG));
			dataSource = BasicDataSourceFactory.createDataSource(prop);
		} catch (IOException e) {
			e.printStackTrace(System.err);
		} catch (Exception e) {
			e.printStackTrace(System.err);
		}
		
	}
	/**
	 * 获取链接
	 * @return
	 */
	public Connection getConn(){
		Connection conn = null;
		if(dataSource!=null){
			try {
				conn = dataSource.getConnection();
				
				conn.setAutoCommit(false);
			} catch (SQLException e) {
				e.printStackTrace(System.err);
			}
			return conn;
		}
		return conn;
	}
	/**
	 * 静态内部类
	 * @author Lian
	 *
	 */
	private static class DBCPUtilsHolder{
		private static DBCPUtils dbcp = new DBCPUtils();
	}
	/**
	 * 工厂方法
	 * @return
	 */
	public static DBCPUtils getInstance(){
		return DBCPUtilsHolder.dbcp;
	}
}
